//
//  SearchViewController.m
//  shanHaiHuiApp
//
//  Created by DS on 2018/3/9.
//  Copyright © 2018年 徐双. All rights reserved.
//

#import "SearchViewController.h"
#import "RootCollectionViewCell.h"
#import "HomeTableViewCell.h"
#import "HotGoodModel.h"
#import "GoodDetailView.h"
//我的界面
//#import "MineViewController.h"

//八张图片模型
#import "CollectModel.h"

//购物车
#import "ShopCarView.h"
//搜索
#import "SearchViewController.h"


#import "PaymentViewController.h"

#import "GoodDetailModel.h"

//存储到本地的model
#import "ShopCarModel.h"

//#import "DispatchViewController.h"

#import "PayMentGoodModel.h"
#import "PayMentSpphModel.h"

#import "PurchaseCarAnimationTool.h"

#import "SpphModel.h"



@interface SearchViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>

{
    NSDictionary * dic;
    NSNumber *spkc;
    
    //购物结算接口接收的数据
    NSDictionary * dicOrder;
    NSMutableArray * arrOrder;
    NSMutableArray * arrSpphList;
    NSString * token;
}

Strong UITableView * tableView;
Strong UIView * headView;
Strong UICollectionView * collectionView;
Strong NSMutableArray *collDataArray;


//头部视图
Strong CLCustomButton * leftBtn;

Strong CLCustomButton * rightBtn;

Strong UIView * lineView;
Strong UIView * livnView2;

//底部购物车视图
Strong UIView * bottomView;
Strong UIImageView * shopImageview;
Strong UILabel * totalPriceLabel;
//销量:
Strong UILabel * numberLabel;
Strong UILabel * countLabel;
Strong UIButton * calculateBtn;

//请选择商品
Strong UIButton * bottomBtn;

Strong UIView * blankView;

Assign int page;
Strong NSMutableArray * dataArray;
Strong HotGoodModel * hotModel;

Strong NSString * orderField;
Strong NSString * orderType;

//存储到本地的模型数组
Strong NSMutableArray *shopcarArray;

//输入框的数量(加)
Strong NSString * countString;
Strong  NSString * pariceLabel;

//输入框的数量(减)
Strong NSString * countString1;
Strong  NSString * pariceLabel1;

Strong ShopCarView * shopCarView;

//保存商品编号
Strong NSString * serialNum;

Strong NSMutableArray * selectedGoods;

Strong NSMutableArray *shopCarDetailArr;

//再保存一个count来保存商品详情里我最后的数量
Assign NSInteger lastCount;

Strong  HomeTableViewCell * cellHome;

//轮播图数组
Strong NSMutableArray * imageArr;

Strong  NSDictionary *dicShopCar;

//购买的商品
Strong NSMutableArray * orderArrSuccess;

//商品批号
Strong NSMutableArray * orderSpphArrSuccess;


Strong NSMutableArray * combArr;


Strong NSMutableArray * shopcartGoodsArray;

@end

//网络
@implementation SearchViewController (NetWorking)

//搜索接口
- (void)getData:(int)page{
    [self showprogressHUD];
    NSMutableDictionary *parameters = @{
                                        @"keyWord":self.textField.text,
                                        @"page":[NSString stringWithFormat:@"%d",page],
                                        @"limit":@10,
                                        @"orderField":self.orderField,
                                        @"orderType":self.orderType
                                        }.mutableCopy;
   
    [[AFAppDotNetAPIClient sharedClient] POST:@"merpspList.do" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
   
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        //[self.dataArray removeAllObjects];
        if ([responseObject[@"code"] intValue] == 0) {
            if (page == 1) {
                self.page = 1;
                [self.dataArray removeAllObjects];
            }
            self.page ++;
    
            for (NSDictionary * dic in responseObject[@"list"]) {
                HotGoodModel * hotModel = [[HotGoodModel alloc] init];
                [hotModel HotGoodModelWithDic:dic];
                [self.dataArray addObject:hotModel];
            }
           if (self.dataArray.count == 0) {

               [self.view addSubview:self.blankView];

           }else{
                [self.view addSubview:self.tableView];
                [self.view addSubview:self.headView];
               // [self.tableView reloadData];
           }
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

//获取单品详情
- (void)getDetailDataWith:(NSString *)spkuId{
    [self showprogressHUD];
    NSDictionary *parameters = @{
                                 @"spbh":spkuId,
                                 
                                 }.mutableCopy;
    [[AFAppDotNetAPIClient sharedClient] POST:@"merpspPage.do" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"code"] intValue] == 0) {
            dic = responseObject[@"erpsp"];
            spkc = responseObject[@"spkc"];
            [self.imageArr removeAllObjects];
            for (NSDictionary *dic in responseObject[@"imagelist"]) {
                [self.imageArr addObject:dic[@"shImagepfilename"]];
            }
            
            //GoodDetailView * detailView = [[UIApplication sharedApplication].delegate.window viewWithTag:2002];
            //detailView.imageArr = self.imageArr;
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

// 将数组转JSON
- (NSData *)toJSONData:(id)theData{
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    
    if ([jsonData length] > 0 && error == nil){
        return jsonData;
    }else{
        return nil;
    }
}

//购物结算接口

- (void)getSaleData{
    arrOrder = [[NSMutableArray alloc]init];
    arrSpphList = [[NSMutableArray alloc] init];
    [self showprogressHUD];
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:5];
    
    NSString * str = nil;
    for (ShopCarModel *model in self.shopCarView.dataArr) {
        NSDictionary *dic = @{@"spbh":model.serialNum,
                              @"spmc":model.name,
                              @"xsdj":model.perMoney,
                              @"xssl":[NSString stringWithFormat:@"%ld",(long)model.goodCount],
                              @"xsje":[NSString stringWithFormat:@"%f",([model.perMoney floatValue] * model.goodCount)]
                              };
        [arr addObject:dic];
        
        str = [[NSString alloc] initWithData:[self toJSONData:arr]
                                    encoding:NSUTF8StringEncoding];
    }
    NSDictionary *parameters = @{
                                 @"cardno":self.shopCarView.textField.text,
                                 @"orderXssl":self.shopCarView.countLabel.text,
                                 @"orderXsje":[self.shopCarView.totalPriceLabel.text substringFromIndex:1],
                                 @"token":[UserModel sharedInstanced].token,
                                 @"orderSps":str
                                 }.mutableCopy;
    
    
    [[AFAppDotNetAPIClient sharedClient] POST:@"mshopping.do" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        
        
        
        if ([responseObject[@"code"] intValue] == 0) {
            
            
            dicOrder = responseObject[@"order"];
            
            [UserModel sharedInstanced].token = responseObject[@"token"];
            
            if (self.orderArrSuccess.count > 0) {
                
                [self.orderArrSuccess removeAllObjects];
            }
            for (NSDictionary * dic in responseObject[@"orderDetailList"]) {
                PayMentGoodModel * model = [[PayMentGoodModel alloc] init];
                [model payMentGoodModelWithDic:dic];
                [self.orderArrSuccess addObject:model];
            }
            
            
            if (self.orderSpphArrSuccess.count > 0) {
                
                [self.orderSpphArrSuccess removeAllObjects];
            }
            
            
            for (NSDictionary * dic in responseObject[@"spphList"]) {
                
                SpphModel * model = [[SpphModel alloc] init];
                [model spphModelWithDic:dic];
                [self.orderSpphArrSuccess addObject:model];
            }
            
            
            if (self.combArr.count > 0) {
                
                [self.combArr removeAllObjects];
            }
            
            for (PayMentGoodModel * model in self.orderArrSuccess) {
                NSString *natureid = model.spbh;
                NSMutableArray *arr = [NSMutableArray arrayWithCapacity:5];
                for (SpphModel * model in self.orderSpphArrSuccess) {
                    NSString *natureid1 = model.fSpbh;
                    if ([natureid1 isEqualToString:natureid]) {
                        [arr addObject:model];
                    }
                }
                [self.combArr addObject:arr];
            }
            
            
            
            PaymentViewController * vc = [[PaymentViewController alloc] init];
            vc.orderDic = dicOrder;
            
            vc.orderArr = self.orderArrSuccess;
            vc.orderAllSpphArr = self.orderSpphArrSuccess;
            
            
            vc.orderSpphArr = self.combArr;
            
            
            vc.token = token;
            vc.passWordAppear = dicOrder[@"isPassword"];
            
            [self.navigationController pushViewController:vc animated:YES];
            
            
        }else{
            ShowMessage(responseObject[@"msg"]);
            
            [UserModel sharedInstanced].token = responseObject[@"token"];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

@end



@implementation SearchViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self NavColor];
    self.orderField = @"name";
    self.orderType = @"asc";
    [self getData:1];
    
}

// 导航颜色
- (void)NavColor{
    
    UINavigationBar * bar = self.navigationController.navigationBar;
    UIImage *bgImage = [UIImage imageWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 64) WihtColor:getColor(navColor) alphe:1.0];
    [bar setBackgroundImage:bgImage forBarMetrics:UIBarMetricsDefault];
    
    
    [bar setShadowImage:[UIImage imageWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 0.1) WihtColor:[UIColor blackColor] alphe:1.0]];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"搜索";
    
   
    

    if ([[self.dict objectForKey:@"totalCount"] isEqualToString:@"0"]) {
        
        [self.view addSubview:self.bottomBtn];
        
    
    }else{
        
         [self.view addSubview:self.bottomView];
        
    }
 
    self.navigationItem.titleView = self.textField;
    
 
}



//调到搜索界面
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
     [textField resignFirstResponder];
    
    [self getData:1];
    return YES;
}

//去掉小数点后面的0
-(NSString*)removeFloatAllZero:(NSString*)string
{
    NSString * testNumber = string;
    NSString * outNumber = [NSString stringWithFormat:@"%@",@(testNumber.floatValue)];
    return outNumber;
}

# pragma mark - Action
//购物结算点击
- (void)calculateBtnClick{
    ShopCarView * shopCarView = [[ShopCarView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT ) selectedHandle:^(NSString * str) {
        
    }];
    
    self.shopCarView = shopCarView;
    
    [shopCarView show];
    
    //这里把购物车的数据缓存到本地
    
    [self getCacheWithData];
    
    [self storeChatLogWithFile];
    
    shopCarView.dict = self.dicShopCar;
    shopCarView.dataArr = self.shopcarArray;
    
    ws(shopCarView)
    shopCarView.getCaulteClick = ^{
        
        [self.view endEditing:YES];
        
        if ([weakshopCarView.textField.text isEqualToString:@""]) {
            
            [[UIApplication sharedApplication].keyWindow makeToast:@"请输入会员卡号" duration:1 position:CSToastPositionCenter];
            return;
        }
        
        [self getSaleData];
        
        [weakshopCarView dismiss];
        
    };
    
    //清空购物车,清空缓存
    shopCarView.getClearClick = ^{
        
        [weakshopCarView dismiss];
        
        BOOL isClearSuccess = [ClearCacheTool clearCacheWithFilePath:filePaths];
        
        if (isClearSuccess) {
            NSLog(@"清除成功");
            self.totalPriceLabel.text = [NSString stringWithFormat:@"￥%.2f",0.00];
            self.countLabel.text = [NSString stringWithFormat:@"%d",0];
            [self.view addSubview:self.bottomBtn];
            
        }else{
            NSLog(@"清除失败");
        }
    };
    
    
    shopCarView.getPlusClick = ^(ShopCarView *view, NSInteger goodCount,NSString * spph) {
        
        for (HotGoodModel * hotModel in self.dataArray) {
            
            if ([hotModel.fSpbh isEqualToString:spph]) {
                
                hotModel.goodCount = goodCount;
                
            }
        }
        
        [self.tableView reloadData];
        
        
    };
    
    shopCarView.getMinusClick = ^(ShopCarView *view, NSInteger goodCount,NSString * spph) {
        
        
        
        
        for (HotGoodModel * hotModel in self.dataArray) {
            
            if ([hotModel.fSpbh isEqualToString:spph]) {
                
                hotModel.goodCount = goodCount;
                
            }
            
            
        }
        
        
        [self.tableView reloadData];
        
    };
    
    
    shopCarView.getTextFieldClick = ^(ShopCarView *view, NSInteger goodCount, NSString *spph) {
        
        for (HotGoodModel * hotModel in self.dataArray) {
            
            if ([hotModel.fSpbh isEqualToString:spph]) {
                
                hotModel.goodCount = goodCount;
                
            }
            
        }
        
        [self.tableView reloadData];
        
        
        
    };
    
    
    
    shopCarView.getDeletedClick = ^(ShopCarView *view, NSInteger goodCount, NSString *spph) {
        
        
        for (HotGoodModel * hotModel in self.dataArray) {
            
            if ([hotModel.fSpbh isEqualToString:spph]) {
                
                hotModel.goodCount = goodCount;
                
            }
            
            
        }
        
        
        [self.tableView reloadData];
        
         [self updateCountLabel];
        
        
        
    };
    
    
    
    
    
    
}

//缓存到本地
- (void)getCacheWithData{
    
    NSArray *arr = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    
    NSString *cachePath = [arr lastObject];
    
    //拼接路径（目标路径）
    NSString *filePath = [cachePath stringByAppendingPathComponent:@"tese.plist"];
    NSLog(@"%@",filePath);
    
    //创建数据
    NSDictionary *content = @{
                              @"totalMoney":self.totalPriceLabel.text,
                              @"totalCount":self.countLabel.text,
                              };
    
    //将数据存到目标路径的文件中(这个时候如果该路径下文件不存在将会自动创建)
    
    //用writeToFile方法写文件会覆盖掉原来的内容
    
    [content writeToFile:filePath atomically:YES];
    
    //读取数据(通过字典的方式读出文件中的内容)
    
    self.dicShopCar = [NSDictionary dictionaryWithContentsOfFile:filePath];
    
    
}

-(void)storeChatLogWithFile
{
    //    获取路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"shopCar.plist"];
    NSFileManager *fileM = [NSFileManager defaultManager];
    //    判断文件是否存在，不存在则直接创建，存在则直接取出文件中的内容
    if (![fileM fileExistsAtPath:filePath]) {
        [fileM createFileAtPath:filePath contents:nil attributes:nil];
    }
    NSMutableArray *chatLogArray = [NSMutableArray arrayWithContentsOfFile:filePath];
    if ((chatLogArray.count == 0)) {
        chatLogArray = [NSMutableArray arrayWithCapacity:1];
    }
    //#warning -----
    [chatLogArray addObjectsFromArray:[self selectedGoods]];
    [chatLogArray addObjectsFromArray:self.dataArr];
    [self addSelectedGoods:chatLogArray selectedGoods:[self selectedGoods]];
    
    
    //    注意 数组中保存的是自定义模型，要想把数组保存在文件中，应该用下面的方法
    //    存
    [NSKeyedArchiver archiveRootObject:chatLogArray toFile:filePath];
    //    取
    self.shopcarArray = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    NSLog(@"array:%@",self.shopcarArray);
    
}

- (NSMutableArray *)selectedGoods {
    NSMutableArray *selectedGoods = [NSMutableArray arrayWithCapacity:5];
    for (HotGoodModel * hotModel in self.dataArray) {
        if (hotModel.goodCount > 0) {
            ShopCarModel *carModel = [[ShopCarModel alloc] init];
            carModel.name = hotModel.fSpmc;
            carModel.perMoney = [NSString stringWithFormat:@"%@",hotModel.fDj2];
            carModel.picImage = hotModel.shImagesfilename;
            
            carModel.textField = [NSString stringWithFormat:@"%ld", (long)hotModel.goodCount];
            
            carModel.totalLabel = [NSString stringWithFormat:@"%.1f", hotModel.goodCount * [hotModel.fDj2 floatValue]];
            carModel.serialNum = hotModel.fSpbh;
            
            [selectedGoods addObject:carModel];
        }
    }
    return selectedGoods;
}

- (void)addSelectedGoods:(NSMutableArray *)storedGoods selectedGoods:(NSMutableArray *)selectedGoods {
    for (int i = 0; i < selectedGoods.count; i++) {
        ShopCarModel *selectedModel = selectedGoods[i];
        BOOL contain = NO;
        for (ShopCarModel *carModel in storedGoods) {
            if ([selectedModel.serialNum isEqualToString:carModel.serialNum]) {
                contain = YES;
                break;
            }
        }
        if (!contain) {
            [storedGoods addObject:selectedModel];
        } else {
            [storedGoods replaceObjectAtIndex:i withObject:selectedModel];
        }
    }
}


#pragma init----
-(UIView *)blankView{
    if (!_blankView) {
        
        if (kDevice_Is_iPhoneX) {
            
             _blankView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - height64  - UNIT_HEIGHT(49) - height20)];
            
        }else{
            
             _blankView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - height64  - UNIT_HEIGHT(49))];
            
        }
        
       
        UIImageView * blankImage = [UIImageView new];
        blankImage.image = [UIImage imageNamed:@"meishangping"];
        blankImage.contentMode = UIViewContentModeScaleAspectFit;
        
        UILabel * blankLabel = [[UILabel alloc] init];
        blankLabel.text = @"没有商品";
        blankLabel.font = DEF_FontSize_18;
        blankLabel.textColor = getColor(@"666666");
        blankLabel.textAlignment = NSTextAlignmentCenter;
        
        [_blankView sd_addSubviews:@[blankImage,blankLabel]];
        
        [blankImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(UNIT_HEIGHT(114));
            make.centerX.mas_equalTo(_blankView.mas_centerX);
            make.height.mas_equalTo(UNIT_HEIGHT(158));
            make.width.mas_equalTo(UNIT_WIDTH(165));
        }];
        
        [blankLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(blankImage.mas_bottom).offset(UNIT_HEIGHT(15));
            make.centerX.mas_equalTo(_blankView.mas_centerX);
            make.height.mas_equalTo(UNIT_HEIGHT(30));
            make.width.mas_equalTo(UNIT_WIDTH(150));
        }];
        
    }
    return _blankView;
}


//输入框
- (UITextField *)textField{
    if (!_textField) {
        _textField  = [[UITextField alloc]initWithFrame:CGRectMake(height20, 26, SCREEN_WIDTH - 100 / WIDTH_5S_SCALE, 30)];
        _textField.font = DEF_FontSize_14;
        _textField.placeholder = @"请录入商品编号、商品名称、商品产地";
        _textField.layer.masksToBounds = YES;
        _textField.layer.cornerRadius = 5;
        _textField.returnKeyType = UIReturnKeySearch;
        _textField.leftView = ({
            UIImageView *leftImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 20)];
            leftImageView.contentMode = UIViewContentModeScaleAspectFit;
            leftImageView.image = [UIImage imageNamed:@"sousuo_icon"];
            leftImageView;
        });
        _textField.leftViewMode = UITextFieldViewModeAlways;
        _textField.backgroundColor = getColor(@"F0F0F0");
        _textField.delegate = self;
        _textField.clearButtonMode = UITextFieldViewModeAlways;
        
        //去调用上面的代码，给这个UITextField的对象添加UIToolbar
        _textField.inputAccessoryView = [self addToolbar];
    }
    return _textField;
}



- (UIView *)headView{
    
    if (!_headView) {
        _headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, UNIT_HEIGHT(43))];
        _headView.backgroundColor = [UIColor whiteColor];
       
        _leftBtn = [[CLCustomButton alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH/2, UNIT_HEIGHT(43)) type:CLCustomButtonRightImageType imageSize:CGSizeMake(8, 8) midmargin:5];
        _leftBtn.isShowSelectBackgroudColor = NO;
        _leftBtn.imageView.image = [UIImage imageNamed:@"xia1"];
        _leftBtn.titleLabel.text = @"名称";
        _leftBtn.titleLabel.textColor = getColor(@"EC4350");
        _leftBtn.titleLabel.font = DEF_FontSize_14;
        _leftBtn.backgroundColor = [UIColor whiteColor];
        _leftBtn.tag = 2001;
        [_leftBtn touchAction:^(CLCustomButton * _Nonnull button) {
           static int i = 0;
            i ++;
            if (i % 2 == 0) {
                self.orderType = @"asc";
                self.leftBtn.imageView.image = [UIImage imageNamed:@"xia1"];
            }else{
                self.orderType = @"desc";
                self.leftBtn.imageView.image = [UIImage imageNamed:@"xiahong1"];
            }
            [self getData:1];
            
        }];
        
        
        _lineView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_leftBtn.frame),0, 0.5, UNIT_HEIGHT(43))];
        _lineView.backgroundColor = getColor(@"F0F0F0");
        
        
        
        _rightBtn = [[CLCustomButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_leftBtn.frame),0, SCREEN_WIDTH/2, UNIT_HEIGHT(43)) type:CLCustomButtonRightImageType imageSize:CGSizeMake(8, 8) midmargin:5];
        _rightBtn.isShowSelectBackgroudColor = NO;
        _rightBtn.imageView.image = [UIImage imageNamed:@"xiahong1"];
        _rightBtn.titleLabel.text = @"价格";
        _rightBtn.titleLabel.textColor = getColor(@"323232");
        _rightBtn.titleLabel.font = DEF_FontSize_14;
        _rightBtn.backgroundColor = [UIColor whiteColor];
        _rightBtn.tag = 2002;
        [_rightBtn touchAction:^(CLCustomButton * _Nonnull button) {
            self.orderField = @"price";
            static int i = 0;
            i ++;
            if (i % 2 == 0) {
                self.orderType = @"asc";
                self.rightBtn.imageView.image = [UIImage imageNamed:@"xia1"];
                
            }else{
                self.orderType = @"desc";
                self.rightBtn.imageView.image = [UIImage imageNamed:@"xiahong1"];
            }
            [self getData:1];
        }];
        
        _livnView2 = [[UIView alloc] init];
        _livnView2.backgroundColor = getColor(dividerColor);
       
        [_headView sd_addSubviews:@[self.leftBtn,self.rightBtn,self.lineView,self.livnView2]];
        
        [self.livnView2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.right.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
            make.height.mas_equalTo(UNIT_HEIGHT(1));
        }];
        
    }
    return _headView;
}


- (UITableView *)tableView{
    if (!_tableView) {
        
        if (kDevice_Is_iPhoneX) {
             _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, UNIT_HEIGHT(43), SCREEN_WIDTH, SCREEN_HEIGHT - UNIT_HEIGHT(43) - UNIT_HEIGHT(49) - height64 - height20) style:UITableViewStyleGrouped];
        }else{
           
             _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, UNIT_HEIGHT(43), SCREEN_WIDTH, SCREEN_HEIGHT - UNIT_HEIGHT(43) - UNIT_HEIGHT(49) - height64) style:UITableViewStyleGrouped];
            
        }
        
        
       
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.sectionFooterHeight = .01;
        _tableView.sectionHeaderHeight = .01;
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0.01)];
        _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0.01)];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self getData:1];
        }];
        
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    }
    return _tableView;
}

- (void)loadMoreData{
    
    
    [_tableView.mj_footer beginRefreshing];
    
   
     [self getData:self.page];
    
    [_tableView.mj_footer endRefreshing];
    
    
    
}

#pragma mark - <UITableViewDelegate , UITableViewDataSource>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HomeTableViewCell * cell = [HomeTableViewCell cellForTableView:tableView];
    //self.cellHome = cell;
    
    cell.model = self.dataArray[indexPath.row];
    
    cell.textField.hidden = YES;
    cell.perLabel.hidden = YES;
    cell.minusBtn.hidden = YES;
    cell.textField.text = [NSString stringWithFormat:@"%ld",cell.model.goodCount ? : 1];
    
    
    
    
    if (cell.model.goodCount > 0) {
        cell.textField.hidden = NO;
        cell.perLabel.hidden = NO;
        cell.minusBtn.hidden = NO;
        
        self.countString = [NSString stringWithFormat:@"%ld",cell.model.goodCount];
        cell.textField.text = self.countString;
        
        CGFloat fdj2 = (CGFloat)[cell.model.fDj2 floatValue];
        
        //去掉小数点末尾的0
        
        NSString * str = [NSString stringWithFormat:@"%f",cell.model.goodCount * fdj2];
        
        NSString *str1 = [self removeFloatAllZero:str];
        
        self.pariceLabel = [NSString stringWithFormat:@"￥%@",str1];
        
        cell.pariceLabel.text = self.pariceLabel;
        
        [self updateCountLabel];

    }
    
 
    //点击加号按钮触发的事件
    cell.getPlusClick = ^(HomeTableViewCell *cell,UITextField * textField,UIImageView *imageView,UIButton * plusBtn) {
        
        [self.view addSubview:self.bottomView];
        
        //加入购物车动画
        
        UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
        
        CGRect rect1 = [_shopImageview convertRect: _shopImageview.bounds toView:window];
        
         CGRect rect2 = [plusBtn convertRect: plusBtn.bounds toView:window];
        
        [[PurchaseCarAnimationTool shareTool] startAnimationandView:imageView
                                                               rect:rect2
                                                        finisnPoint:CGPointMake(rect1.origin.x, rect1.origin.y)
                                                        finishBlock:^(BOOL finish) {
                                                            
                                                            [PurchaseCarAnimationTool shakeAnimation:_shopImageview];
                                                        }];
        
        
        
        
        [self.view addSubview:self.bottomView];
        
        [UIView animateWithDuration:1 animations:^{
            cell.textField.hidden = NO;
            cell.perLabel.hidden = NO;
            cell.minusBtn.hidden = NO;
            cell.model.goodCount += 1;
           
             
            self.countString = [NSString stringWithFormat:@"%ld",cell.model.goodCount];
            cell.textField.text = self.countString;
            
            CGFloat fdj2 = (CGFloat)[cell.model.fDj2 floatValue];
             
            
            //去掉小数点末尾的0
            
            NSString * str = [NSString stringWithFormat:@"%f",cell.model.goodCount * fdj2];
            
            NSString *str1 = [self removeFloatAllZero:str];
            
            self.pariceLabel = [NSString stringWithFormat:@"￥%@",str1];
            
            cell.pariceLabel.text = self.pariceLabel;
            
            [self updateCountLabel];
            
        }];
    };
    
    //点击减号按钮触发的事件
    cell.getMinusClick = ^(HomeTableViewCell *cell,UITextField * textField) {
        
        
        [UIView animateWithDuration:1 animations:^{
            
            cell.model.goodCount -= 1;
            self.countString1 = [NSString stringWithFormat:@"%ld",cell.model.goodCount];
            cell.textField.text = self.countString1;
            CGFloat fdj2 = (CGFloat)[cell.model.fDj2 floatValue];
            
            
            //去掉小数点末尾的0
            
            NSString * str1 = [NSString stringWithFormat:@"%f",cell.model.goodCount * fdj2];
            
            NSString * strSub = [self removeFloatAllZero:str1];
            
            self.pariceLabel1 = [NSString stringWithFormat:@"￥%@",strSub];
            cell.pariceLabel.text = self.pariceLabel1;
            if([cell.textField.text isEqualToString:@"0"]){
                cell.textField.hidden = YES;
                cell.perLabel.hidden = YES;
                cell.minusBtn.hidden = YES;
                cell.pariceLabel.text = [NSString stringWithFormat:@"￥%@",cell.model.fDj2];
                
            }
            
            [self updateCountLabel];
            
        }];
    };
    
    
    
    cell.getTextFieldClick = ^(HomeTableViewCell *cell,UITextField * textField) {
        
        [UIView animateWithDuration:1 animations:^{
            
            
            
            cell.model.goodCount = [textField.text integerValue];
            
            CGFloat fdj2 = (CGFloat)[cell.model.fDj2 floatValue];
            
            NSString * str1 = [NSString stringWithFormat:@"%f",cell.model.goodCount * fdj2];
            
            NSString * strSub = [self removeFloatAllZero:str1];
            self.pariceLabel1 = [NSString stringWithFormat:@"￥%@",strSub];
            cell.pariceLabel.text = self.pariceLabel1;
            if([cell.textField.text isEqualToString:@"0"]){
                cell.textField.hidden = YES;
                cell.perLabel.hidden = YES;
                cell.minusBtn.hidden = YES;
                cell.pariceLabel.text = [NSString stringWithFormat:@"￥%@",cell.model.fDj2];
            }
            
            [self updateCountLabel];
        }];
    };
    
    return cell;
}



- (void)updateCountLabel {
 
    NSString *  str = [self.dict objectForKey:@"totalMoney"];
   
    NSString * str1 = [str stringByReplacingOccurrencesOfString:@"￥" withString:@""];
  
    NSInteger count = [[self.dict objectForKey:@"totalCount"] integerValue];
    CGFloat totalPrice = [str1 floatValue];
    
  
    
    for (HotGoodModel *model in self.dataArray) {
        count += model.goodCount;
        CGFloat fdj2 = (CGFloat)[model.fDj2 floatValue];
        totalPrice += model.goodCount * fdj2;
    }
    
    NSString * totalStr = [NSString stringWithFormat:@"%f",totalPrice];
    NSString * totalStr1 = [self removeFloatAllZero:totalStr];
    _totalPriceLabel.text = [NSString stringWithFormat:@"￥%@",totalStr1];
    _countLabel.text = [NSString stringWithFormat:@"%ld",(long)count];
    if ([self.countLabel.text isEqualToString:@"0"]) {
        [self.view addSubview:self.bottomBtn];
    }
    
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UNIT_HEIGHT(120);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    GoodDetailView * detailView = [[GoodDetailView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) selectedHandle:^(NSString * str) {
    }];
    detailView.tag = 2001;
    self.hotModel = self.dataArray[indexPath.row];
    
    [self getDetailDataWith:self.hotModel.fSpbh];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:5];
    dic[@"fSpmc"] = self.hotModel.fSpmc;
    dic[@"fDj2"] = self.hotModel.fDj2;
    dic[@"fCd"] = self.hotModel.fCd;
    dic[@"fDw"] = self.hotModel.fDw;
    dic[@"fSpgg"] = self.hotModel.fSpgg;
    detailView.model = dic;
    detailView.spkc = spkc;
    detailView.goodCount = self.hotModel.goodCount;
    
    
    [detailView show];
    
    if (self.hotModel.goodCount > 0) {
        
        detailView.textField.hidden = NO;
        detailView.perLabel.hidden = NO;
        detailView.minusBtn.hidden = NO;
        detailView.textField.text = [NSString stringWithFormat:@"%ld",detailView.goodCount ? : 1];
        
        
    }else{
        
        detailView.textField.hidden = YES;
        detailView.perLabel.hidden = YES;
        detailView.minusBtn.hidden = YES;
        detailView.textField.text = [NSString stringWithFormat:@"%ld",detailView.goodCount ? : 1];
        
    }
    
    
    
    
    ws(detailView)
    detailView.getPlusClick = ^(GoodDetailView *view) {
        [self.view addSubview:self.bottomView];
        
        [UIView animateWithDuration:1 animations:^{
            weakdetailView.textField.hidden = NO;
            weakdetailView.perLabel.hidden = NO;
            weakdetailView.minusBtn.hidden = NO;
            weakdetailView.goodCount += 1;
            
            
            self.hotModel.goodCount = weakdetailView.goodCount;
            [self.tableView reloadData];
            
            
            
            //对应购物车的总价和数量都在变
            NSString * countString = [NSString stringWithFormat:@"%ld",weakdetailView.goodCount];
            weakdetailView.textField.text = countString;
            
            
            
            CGFloat fdj2 = (CGFloat)[weakdetailView.model[@"fDj2"] floatValue];
            
            NSString * str = [NSString stringWithFormat:@"%f",weakdetailView.goodCount * fdj2];
            NSString * str1 = [self removeFloatAllZero:str];
            
            weakdetailView.pariceLabel.text = [NSString stringWithFormat:@"￥%@",str1];
        }];
    };
    
    
    detailView.getMinusClick = ^(GoodDetailView *view) {
        
        [UIView animateWithDuration:1 animations:^{
            
            weakdetailView.goodCount -= 1;
            
            self.hotModel.goodCount = weakdetailView.goodCount;
            [self.tableView reloadData];
            
            NSString * countString = [NSString stringWithFormat:@"%ld",weakdetailView.goodCount];
            weakdetailView.textField.text = countString;
            CGFloat fdj2 = (CGFloat)[weakdetailView.model[@"fDj2"] floatValue];
            
            NSString * strMiu = [NSString stringWithFormat:@"%f",weakdetailView.goodCount * fdj2];
            NSString * strMiuy = [self removeFloatAllZero:strMiu];
            weakdetailView.pariceLabel.text = [NSString stringWithFormat:@"￥%@",strMiuy];
            if([weakdetailView.textField.text isEqualToString:@"0"]){
                weakdetailView.textField.hidden = YES;
                weakdetailView.perLabel.hidden = YES;
                weakdetailView.minusBtn.hidden = YES;
                weakdetailView.pariceLabel.text = [NSString stringWithFormat:@"￥%@",weakdetailView.model[@"fDj2"]];
            }
            
        }];
    };
    
    weakdetailView.getTextFieldClick = ^(GoodDetailView * view) {
        
        [UIView animateWithDuration:1 animations:^{
            
            self.hotModel.goodCount = weakdetailView.goodCount;
            [self.tableView reloadData];
            
            
            self.countString1 = [NSString stringWithFormat:@"%ld",weakdetailView.goodCount];
            // weakdetailView.textField.text = self.countString1;
            CGFloat fdj2 = (CGFloat)[weakdetailView.model[@"fDj2"] floatValue];
            
            NSString * str = [NSString stringWithFormat:@"%f",weakdetailView.goodCount * fdj2];
            NSString * str1 = [self removeFloatAllZero:str];
            
            self.pariceLabel1 = [NSString stringWithFormat:@"￥%@",str1];
            weakdetailView.pariceLabel.text = self.pariceLabel1;
            if([weakdetailView.textField.text isEqualToString:@"0"]){
                weakdetailView.textField.hidden = YES;
                weakdetailView.perLabel.hidden = YES;
                weakdetailView.minusBtn.hidden = YES;
                weakdetailView.pariceLabel.text = [NSString stringWithFormat:@"￥%@",weakdetailView.model[@"fDj2"]];
            }
            
        }];
    };
    
    //点击单品详情的加入购物车功能,下面额数据也跟着变,然后对应cell的加减号也变
    detailView.getJoinShopCarClick = ^(GoodDetailView *view) {
        
        NSInteger count = 0;
        CGFloat totalPrice = 0;
        
        count += weakdetailView.goodCount;
        CGFloat fdj2 = (CGFloat)[weakdetailView.model[@"fDj2"] floatValue];
        totalPrice += weakdetailView.goodCount * fdj2;
        
        NSString * str1 = [NSString stringWithFormat:@"%f",totalPrice];
        NSString * str = [self removeFloatAllZero:str1];
        _totalPriceLabel.text = [NSString stringWithFormat:@"￥%@",str];
        _countLabel.text = [NSString stringWithFormat:@"%ld",(long)count];
        
        //这里把购物车的数据缓存到本地
        
        [weakdetailView dismiss];
        
        if ([self.countLabel.text isEqualToString:@"0"]) {
            [self.view addSubview:self.bottomBtn];
        }
    };
}



// 底部视图
//请选择商品
- (UIButton *)bottomBtn{
    
    if (!_bottomBtn) {
        
        if (kDevice_Is_iPhoneX) {
            _bottomBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - height20 - UNIT_HEIGHT(49) - height64, SCREEN_WIDTH, UNIT_HEIGHT(49))];
        }else{
            
            _bottomBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT  - UNIT_HEIGHT(49) - height64, SCREEN_WIDTH, UNIT_HEIGHT(49))];
            
        }
        
        
        [_bottomBtn setTitle:@"请挑选商品" forState:UIControlStateNormal];
        [_bottomBtn setBackgroundColor:getColor(@"949494")];
        [_bottomBtn setTitleColor:getColor(@"323232") forState:UIControlStateNormal];
        _bottomBtn.enabled = NO;
        _bottomBtn.titleLabel.font = DEF_FontSize_14;
        
    }
    return _bottomBtn;
}


//显示购物车
- (UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.tableView.frame), SCREEN_WIDTH, UNIT_HEIGHT(49))];
        _bottomView.backgroundColor = [UIColor whiteColor];
        
        _shopImageview = [UIImageView new];
        _shopImageview.contentMode = UIViewContentModeScaleAspectFit;
        _shopImageview.image = [UIImage imageNamed:@"gouwuche"];
        
        _totalPriceLabel = [[UILabel alloc] init];
        _totalPriceLabel.textColor = getColor(@"EC4350");
        _totalPriceLabel.font = DEF_FontSize_18;
        _totalPriceLabel.text = @"￥0.00";
        
        _numberLabel = [[UILabel alloc] init];
        _numberLabel.font = DEF_FontSize_14;
        _numberLabel.textColor = getColor(@"323232");
        _numberLabel.text = @"销量 :";
        
        _countLabel = [[UILabel alloc] init];
        _countLabel.font =DEF_FontSize_14;
        _countLabel.textColor = getColor(@"323232");
        _countLabel.text = @"0";
        
        _calculateBtn = [[UIButton alloc] init];
        _calculateBtn .backgroundColor = getColor(@"EC4350");
        [_calculateBtn setTitle:@"购物结算" forState:UIControlStateNormal];
        [_calculateBtn setTitleColor:getColor(@"FFFFFF") forState:UIControlStateNormal];
        [_calculateBtn addTarget:self action:@selector(calculateBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
        self.totalPriceLabel.text = [self.dict objectForKey:@"totalMoney"];
        self.countLabel.text = [self.dict objectForKey:@"totalCount"];
        
        [_bottomView sd_addSubviews:@[_shopImageview,_totalPriceLabel,_numberLabel,_countLabel,_calculateBtn]];
        
        _shopImageview.sd_layout
        .topSpaceToView(_bottomView ,UNIT_HEIGHT(12))
        .leftSpaceToView(_bottomView , UNIT_HEIGHT(16))
        .widthIs(UNIT_WIDTH(30))
        .heightIs(UNIT_HEIGHT(30));
        
        _totalPriceLabel.sd_layout
        .centerYEqualToView(_shopImageview)
        .leftSpaceToView(_shopImageview , UNIT_HEIGHT(6))
        .widthIs(UNIT_WIDTH(100))
        .heightIs(UNIT_HEIGHT(30));
        
        _numberLabel.sd_layout
        .centerYEqualToView(_shopImageview)
        .leftSpaceToView(_totalPriceLabel, UNIT_HEIGHT(6))
        .widthIs(UNIT_WIDTH(50))
        .heightIs(UNIT_HEIGHT(30));
        
        _countLabel.sd_layout
        .centerYEqualToView(_shopImageview)
        .leftSpaceToView(_numberLabel, UNIT_HEIGHT(0))
        .widthIs(UNIT_WIDTH(60))
        .heightIs(UNIT_HEIGHT(30));
        
        [_calculateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(0);
            make.top.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
            make.width.mas_equalTo(UNIT_WIDTH(100));
        }];
    }
    return _bottomView;
}


#pragma mark-- 懒加载
- (NSMutableArray *)dataArray{
    
    if (!_dataArray) {
        _dataArray = @[
                       
                       ].mutableCopy;
    }
    
    return _dataArray;
}

- (NSMutableArray *)imageArr{
    if (!_imageArr) {
        _imageArr = @[
                      ].mutableCopy;
    }
    return _imageArr;
}

- (NSMutableArray *)shopcarArray{
    
    if (!_shopcarArray) {
        _shopcarArray = @[
                          ].mutableCopy;
    }
    return _shopcarArray;
}

- (NSMutableArray *)shopCarDetailArr{
    
    if (!_shopCarDetailArr) {
        _shopCarDetailArr = @[
                              
                              ].mutableCopy;
        
    }
    return _shopCarDetailArr;
}

- (UIToolbar *)addToolbar
{
    
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    
    UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    UIBarButtonItem *bar = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(numberFieldCancle)];
    
    
    toolbar.items = @[space, bar];
    
    return toolbar;
}

- (void)numberFieldCancle{
    
    [self.textField resignFirstResponder];
    
}


- (NSMutableArray *)orderArrSuccess{
    
    if (!_orderArrSuccess) {
        
        _orderArrSuccess = @[
                             
                             ].mutableCopy;
    }
    return _orderArrSuccess;
}

- (NSMutableArray *)orderSpphArrSuccess{
    
    if (!_orderSpphArrSuccess) {
        
        _orderSpphArrSuccess = @[
                                 
                                 ].mutableCopy;
        
    }
    return _orderSpphArrSuccess;
}

- (NSMutableArray *)combArr{
    
    if (!_combArr) {
        
        _combArr = @[].mutableCopy;
    }
    
    return _combArr;
    
}




@end
